import json

import requests

from funcall.AbstractFunCall import AbstractFunCall, fun_call_log_debug, FUN_CALL_REMARK

from conf.config import AppConf
from funcall.FuncallInfo import FuncallInfo, funcall_info_to_mysql
from funcalltools.file_utils import fc_write_file, fc_read_file
from funcall.funcall_result import FuncallResult
from funcalltools.json_utils import to_json
from utils.log_utils import log_title


def searxng(query: str):
    #浏览器可以访问这个出现搜索结果
    #http://localhost:8080/search?q=%E5%95%8A%E6%98%AF%E9%9D%9E%E5%BE%97%E5%A4%B1&format=json
    url = "http://localhost:8080/search"
    params = {"q": str(query), "format": "json"}
    # params["content_length"] = "long"
    params["full_content"] = "true"
    response = requests.get(url, params=params)
    # print(response)
    results_dict = response.json()
    # print(type(results_dict))
    # print(json.dumps(results_dict, indent=4, ensure_ascii=False))
    results_list = results_dict.get("results", [])
    web_result = ""
    if results_list:
        for results_item in results_list[:5]:
            title = results_item.get("title", "")
            content = results_item.get("content", "")
            url = results_item.get("url", "")
            if title and content:
                web_result = (
                        web_result + "标题：" + title + "\n" + "内容：" + content + "\n"+"链接:"+url+"\n"
                )
    return web_result


class searx_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "searx"
        self.description = "searx 搜索"

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "search_text": {
                    "type": "string",
                    "description": f"要搜索的文本内容, 搜索的结果内容存放在返回json的content中,配合'access_www'工具去查找你想知道的内容)"
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "search_text"
        ]

    def action(self, jsonRoot):
        arg_tmp = jsonRoot['search_text']
        funcallInfo = FuncallInfo(description="searx", req_args=arg_tmp)
        funcallInfo.remark=jsonRoot['remark']
        funcall_info_to_mysql(funcallInfo)

        results=searxng(arg_tmp)
        # import pandas as pd
        # df=pd.DataFrame(results)
        # print(df.head())
        content_tmp=to_json(results)
        funcallInfo.log_text=content_tmp
        fun_call_log_debug(funcallInfo)
        return FuncallResult(msg="成功",content=content_tmp).to_json()


if __name__ == '__main__':
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = searx_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {"search_text": "solon是什么"}
    args = {"search_text": "杭州天气如何,现在几点了"}
    result = cw.call(args)

    # 打印结果
    print((result))
